package com.epam.cdp.web;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import javax.ejb.EJB;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.epam.cdp.ejb.async.AsyncBean;

public class AsyncBackingBean {
	
	private final static Log log = LogFactory.getLog(AsyncBackingBean.class);
	
	private String text;
	
	@EJB
	private AsyncBean asyncBean;
	
	public void doOperation() {
		asyncBean.veryLongOperation();
	}

	public void initString() throws InterruptedException {
		Future<String> futureResult = asyncBean.getString();
		someLongRunningMethod();
		try {
			text = futureResult.get(3, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			log.error(e);
		} catch (ExecutionException e) {
			log.error("Invocation exception", e.getCause());
		} catch (TimeoutException e) {
			log.error("Waiting to long ", e);
			futureResult.cancel(true);
			Thread.sleep(2000);
			text = "Request was canceled via timeout";
		}
	}
	
	private void someLongRunningMethod() {}
	
	public AsyncBean getAsyncBean() {
		return asyncBean;
	}

	public void setAsyncBean(AsyncBean asyncBean) {
		this.asyncBean = asyncBean;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}
	
}
